package com.leyou.sh.gateway.filter;

import com.leyou.sh.auth.dto.JwtConstants;
import com.leyou.sh.auth.dto.Payload;
import com.leyou.sh.auth.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.servlet.http.Cookie;

import java.util.concurrent.TimeUnit;

import static com.leyou.sh.auth.dto.JwtConstants.COOKIE_NAME;
import static com.leyou.sh.auth.dto.JwtConstants.KEY_PREFIX;

/**
 * @author balisong_fcs
 * @date 2021/1/15 20:31
 * @desc
 */
@Component
@Order
public class RefreshLoginExpireTimeFilter implements GlobalFilter {
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //如果用户已经登录,则重置redis对应的jti的国企时间
        //如果没有登录,直接放行
        ServerHttpRequest request = exchange.getRequest();
        HttpCookie cookie = request.getCookies().toSingleValueMap().get(COOKIE_NAME);

        //没有登录,cookie为空
        if (cookie == null) {
            return chain.filter(exchange);
        }
        try {
            Payload payload = jwtUtils.parseJwt(cookie.getValue());

            //无异常,则说明前后台一致,在登录状态,实现重置jti时间业务
            String key = KEY_PREFIX + payload.getUserDetail().getId();
            this.redisTemplate.expire(key, 30, TimeUnit.MINUTES);

            return chain.filter(exchange);

        } catch (Exception e) {
            return chain.filter(exchange);
        }
    }
}
